package com.youzhi.backend.config;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @author mengxu
 */
@Configuration
public class ShiroConfig {


    @Autowired
    private DataSource dataSource;

    public static Long session_milliseconds_time_out = 30 * 24 * 60 * 60 * 1000L;


    /**
     * 放开所有路径权限用注解来细粒度控制
     *
     * @return
     */
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/**", "anon");
        return chainDefinition;
    }


    @Bean
    public Realm realm() {
        JdbcRealm jdbcRealm = new JdbcRealm();
        jdbcRealm.setDataSource(dataSource);
        jdbcRealm.setAuthenticationQuery("select password from User where name = ? ;");
        jdbcRealm.setUserRolesQuery(" select b.roleCode from User a join userRole b on a.id = b.userId where a.name = ? ;");
        jdbcRealm.setPermissionsQuery("select privilegeCode from rolePrivilege where roleCode = ? ;");
        //如果不设置 permissionsLookupEnabled = true,需要自己去实现RolePermissionResolver接口
        jdbcRealm.setPermissionsLookupEnabled(true);
        return jdbcRealm;
    }


}

